#!/usr/bin/env node

/**
 * Update build-release.xcconfig with correct profile and developer values for app signing
 */
var path = require('path');
var fs = require('fs');
stat = fs.stat;
var COMMON_URL = './platforms/android/app/';

// @deprecated
fs.exists("../../platforms/ios", function (exists) {
    return true;
    if (exists) {
        var PROFILE_UUID_TEMPLATE_VAL = '%PROFILE_UUID%';
        var PROFILE_UUID_ENV_VAR = process.env.PROFILE_UUID;
        var DEVELOPER_NAME_REGEX_GLOBAL = /%DEVELOPER_NAME%/g;
        var DEVELOPER_NAME_ENV_VAR = process.env.DEVELOPER_NAME;

        var xcconfigFinal = path.resolve(__dirname, '../../platforms/ios/cordova/build-release.xcconfig');
        var xcconfigTemplate = path.resolve(__dirname, '../../sh/release/xcconfig/build-release.xcconfig.template');

        fs.readFile(xcconfigTemplate, 'utf8', function (err, data) {
            if (err) {
                return console.log(err);
            }

            var result = data.replace(PROFILE_UUID_TEMPLATE_VAL, PROFILE_UUID_ENV_VAR)
                .replace(DEVELOPER_NAME_REGEX_GLOBAL, DEVELOPER_NAME_ENV_VAR);

            fs.writeFile(xcconfigFinal, result, 'utf8', function (err) {
                if (err) return console.log('No directory Found for cordova iOS! Skipping xcconfig creation. ', err);
                console.log('Cordova iOS build-release.xcconfig updated with profile and developer values.')
            });
        });
    }
});
var copy = function (src, dst) {
    // 读取目录中的所有文件/目录
    fs.readdir(src, function (err, paths) {
        if (err) {
            throw err;
        }
        paths.forEach(function (path) {
            var _src = src + '/' + path,
                _dst = dst + '/' + path,
                readable, writable;

            stat(_src, function (err, st) {
                if (err) {
                    throw err;
                }

                // 判断是否为文件
                if (st.isFile()) {
                    // 创建读取流
                    readable = fs.createReadStream(_src);
                    // 创建写入流
                    writable = fs.createWriteStream(_dst);
                    // 通过管道来传输流
                    readable.pipe(writable);
                }
                // 如果是目录则递归调用自身
                else if (st.isDirectory()) {
                    exists(_src, _dst, copy);
                }
            });
        });
    });
};
// 在复制目录前需要判断该目录是否存在，不存在需要先创建目录
var exists = function (src, dst, callback) {
    fs.exists(dst, function (exists) {
        // 已存在
        if (exists) {
            callback(src, dst);
        }
        // 不存在
        else {
            fs.mkdir(dst, function () {
                callback(src, dst);
            });
        }
    });
};

// 复制目录
exists(COMMON_URL + 'src/main/jniLibs', COMMON_URL + './libs', copy);